package com.froggyware.tadpole.core.impl;

import com.froggyware.tadpole.core.MigrationException;
import com.froggyware.tadpole.core.Serializer;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: mst
 * Date: Sep 6, 2011
 * Time: 11:37:52 PM
 * To change this template use File | Settings | File Templates.
 */
public class JacksonSerializer implements Serializer {

    private ObjectMapper mapper = new ObjectMapper();

    public JacksonSerializer() {
        mapper.configure(SerializationConfig.Feature.AUTO_DETECT_FIELDS, true);
        mapper.configure(SerializationConfig.Feature.AUTO_DETECT_IS_GETTERS, true);
        mapper.configure(SerializationConfig.Feature.AUTO_DETECT_GETTERS, true);
        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public byte[] serialize(Object o) {
        try {
            return mapper.writeValueAsBytes(o);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object unserialize(byte[] data, Class rootClass) throws MigrationException {
        try {
            Object o = mapper.readValue(data, rootClass);
            return o;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
